from django import template
from datetime import datetime

register = template.Library()


@register.filter(name='time_since')
def filter_datetime(value):
    """
    time距离现在的时间间隔
    1. 如果时间间隔小于1分钟以内，那么就显示“刚刚”
    2. 如果是大于1分钟小于1小时，那么就显示“xx分钟前”
    3. 如果是大于1小时小于24小时，那么就显示“xx小时前”
    4. 如果是大于24小时小于30天以内，那么就显示“xx天前”
    5. 否则就是显示具体的时间 2017/10/20 16:15
    """
    if isinstance(value, datetime):
        now = datetime.now()
        diff = (now - value).total_seconds()
        if diff < 60:
            return '刚刚'
        elif 60 <= diff < 60 * 60:
            minute = int(diff / 60)
            return '%s分钟前' % minute
        elif 60 * 60 <= diff < 24 * 60 * 60:
            hours = int(diff / 60 / 60)
            return '%s小时前' % hours
        elif 24 * 60 * 60 <= diff < 30 * 24 * 60 * 60:
            days = int(diff/24/60/60)
            return '%s天前' % days
        else:
            return value.strftime("%Y/%m/%d %H:%M")
    else:
        return value


